// LeanCloud 初始化
const APP_ID = 'jyP5Gj0JKvrrBEJAqcTPE7Cl-gzGzoHsz'; // 替换为你的LeanCloud App ID
const APP_KEY = 'sRT5sxlomwR7VTg9zNJFCURv'; // 替换为你的LeanCloud App Key
const SERVER_URL = 'https://jyp5gj0j.lc-cn-n1-shared.com'; // 替换为你的LeanCloud服务器地址

AV.init({
    appId: APP_ID,
    appKey: APP_KEY,
    serverURLs: SERVER_URL
});

// 全局变量
let currentUser = null;
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true;

// DOM元素
const canvas = document.getElementById('drawing-canvas');
const ctx = canvas.getContext('2d');
const authDialog = new mdui.Dialog('#auth-dialog');
const authTab = new mdui.Tab('#auth-tab');
const authBtn = document.getElementById('auth-btn');
const authText = document.getElementById('auth-text');
const saveBtn = document.getElementById('save-btn');
const clearBtn = document.getElementById('clear-btn');
const cancelAuthBtn = document.getElementById('cancel-auth');
const confirmAuthBtn = document.getElementById('confirm-auth');

// 初始化画布
function initCanvas() {
    canvas.width = canvas.offsetWidth;
    canvas.height = canvas.offsetHeight;
    
    ctx.strokeStyle = '#BADA55';
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';
    ctx.lineWidth = 5;
}

// 绘图函数
function draw(e) {
    if (!isDrawing) return;
    
    ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(e.offsetX, e.offsetY);
    ctx.stroke();
    
    [lastX, lastY] = [e.offsetX, e.offsetY];
    
    hue++;
    if (hue >= 360) hue = 0;
    
    if (ctx.lineWidth >= 50 || ctx.lineWidth <= 1) {
        direction = !direction;
    }
    
    if (direction) {
        ctx.lineWidth++;
    } else {
        ctx.lineWidth--;
    }
}

// 保存绘图到LeanCloud
async function saveDrawing() {
    if (!currentUser) return;
    
    const dataURL = canvas.toDataURL('image/png');
    
    const Drawing = AV.Object.extend('Drawing');
    const drawing = new Drawing();
    
    drawing.set('image', dataURL);
    drawing.set('author', currentUser);
    
    try {
        await drawing.save();
        mdui.snackbar({
            message: '保存成功',
            position: 'right-top'
        });
    } catch (error) {
        console.error('保存失败:', error);
        mdui.snackbar({
            message: '保存失败: ' + error.message,
            position: 'right-top'
        });
    }
}

// 加载用户绘图
async function loadUserDrawing() {
    if (!currentUser) return;
    
    const query = new AV.Query('Drawing');
    query.equalTo('author', currentUser);
    query.descending('createdAt');
    
    try {
        const result = await query.first();
        if (result) {
            const img = new Image();
            img.onload = function() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(img, 0, 0);
            };
            img.src = result.get('image');
        }
    } catch (error) {
        console.error('加载失败:', error);
    }
}

// 清空画布
function clearCanvas() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

// 用户登录
async function login(username, password) {
    try {
        currentUser = await AV.User.logIn(username, password);
        updateUIAfterLogin();
        mdui.snackbar({
            message: '登录成功',
            position: 'right-top'
        });
        loadUserDrawing();
    } catch (error) {
        console.error('登录失败:', error);
        mdui.snackbar({
            message: '登录失败: ' + error.message,
            position: 'right-top'
        });
    }
}

// 用户注册
async function register(username, email, password) {
    const user = new AV.User();
    user.setUsername(username);
    user.setEmail(email);
    user.setPassword(password);
    
    try {
        currentUser = await user.signUp();
        updateUIAfterLogin();
        mdui.snackbar({
            message: '注册成功',
            position: 'right-top'
        });
    } catch (error) {
        console.error('注册失败:', error);
        mdui.snackbar({
            message: '注册失败: ' + error.message,
            position: 'right-top'
        });
    }
}

// 用户登出
function logout() {
    AV.User.logOut();
    currentUser = null;
    updateUIAfterLogout();
    mdui.snackbar({
        message: '已登出',
        position: 'right-top'
    });
}

// 更新登录后的UI
function updateUIAfterLogin() {
    authText.textContent = currentUser.getUsername();
    saveBtn.disabled = false;
    authBtn.onclick = logout;
}

// 更新登出后的UI
function updateUIAfterLogout() {
    authText.textContent = '登录/注册';
    saveBtn.disabled = true;
    authBtn.onclick = showAuthDialog;
}

// 显示登录对话框
function showAuthDialog() {
    authDialog.open();
}

// 检查当前用户
function checkCurrentUser() {
    currentUser = AV.User.current();
    if (currentUser) {
        updateUIAfterLogin();
        loadUserDrawing();
    } else {
        updateUIAfterLogout();
    }
}

// 事件监听
canvas.addEventListener('mousedown', (e) => {
    isDrawing = true;
    [lastX, lastY] = [e.offsetX, e.offsetY];
});

canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);

authBtn.addEventListener('click', showAuthDialog);
saveBtn.addEventListener('click', saveDrawing);
clearBtn.addEventListener('click', clearCanvas);

cancelAuthBtn.addEventListener('click', () => authDialog.close());

confirmAuthBtn.addEventListener('click', () => {
    const activeTab = document.querySelector('.mdui-tab-active').getAttribute('href');
    
    if (activeTab === '#login-panel') {
        const username = document.getElementById('login-username').value;
        const password = document.getElementById('login-password').value;
        login(username, password);
    } else {
        const username = document.getElementById('register-username').value;
        const email = document.getElementById('register-email').value;
        const password = document.getElementById('register-password').value;
        register(username, email, password);
    }
    
    authDialog.close();
});

// 初始化
window.addEventListener('load', () => {
    initCanvas();
    checkCurrentUser();
});

window.addEventListener('resize', initCanvas);